<?php

class Nuo_Session_File extends Nuo_Session_Abstract
{
	/**
	 * Read session data
	 *
	 * @param string $id
	 * @return string
	 */
	public function read($id)
	{

		$filename = TEMPORARY_DIR . 'session/' . $id;

		if (!file_exists($filename))
		{
			return '';
		}

		$item = unserialize(file_get_contents($filename));

		if ($item['expired_at'] < time())
		{
			return '';
		}

		/**
		 * session is exsists!
		 */
		$this -> _exsists = TRUE;

		/**
		 * set session life time
		 */
		$this -> setLifetime($item['lifetime']);

		return $item['data'];
	}

	/**
	 * Write session data
	 *
	 * @param string $id
	 * @param string $data
	 * @return boolean
	 */
	public function write($id, $data)
	{
		$file = TEMPORARY_DIR . 'session/' . $id;
		
		$lifetime = $this -> getLifetime();
		
		$time = time();

		if ($fp = fopen($file, 'w'))
		{

			$data = array(
				'lifetime' => $lifetime,
				'modified_at' => $time,
				'expired_at' => $time + $lifetime,
				'data' => $data
			);
			$message = serialize($data);
			fwrite($fp, $message);
		}
		return TRUE;
	}

	/**
	 * Destroy session
	 * @param string $id
	 * @return TRUE
	 */
	public function destroy($id)
	{
		$file = TEMPORARY_DIR . 'session/' . $id;

		@unlink($file);

		return TRUE;
	}

	/**
	 * Garbage Collection
	 * @TODO implement clear file that does not touch session lifetime
	 * @param int $maxlifetime
	 * @return true
	 */
	public function gc($maxlifetime)
	{
		return TRUE;
	}

}
